package com.ycb.bookserver.Aspect;

import com.book.constant.AutoFillConstant;
import com.book.context.BaseContext;
import com.book.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.ycb.bookserver.annotation.AutoFill;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(*com.book.mapper.*.*(..)&&@annotation(com.book.annotation.AutoFill)")
    public void AutoFillPointCut() {}
    @Before("AutoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException {
        log.info("开始进行公共字段填充");
        //获取当前截取到的方法的操作类型
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);//获得注解对象
        OperationType operationType = autoFill.value();
        //获取参数
        Object args[] = joinPoint.getArgs();//获取所用参数对象
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];

        //公共属性统一赋值
        LocalDateTime now = LocalDateTime.now();
        Long currentID = BaseContext.getCurrentId();
        //通过反射赋值
        if (operationType == OperationType.INSERT) {
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUserId = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_USER_ID, Long.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setCreateTime.invoke(entity, now);
                setUserId.invoke(entity, currentID);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentID);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (operationType == OperationType.UPDATE) {

            try {

                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);


                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentID);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
